package cn.huiyunche.bms.web.controller;

import cn.huiyunche.bms.backend.bo.PayableBillBO;
import cn.huiyunche.bms.backend.bo.PaymentBO;
import cn.huiyunche.bms.backend.query.PayableBillConditions;
import cn.huiyunche.bms.backend.query.WayBillDetailConditions;
import cn.huiyunche.bms.backend.service.PayableService;
import cn.huiyunche.bms.web.query.PayableBillQuery;
import cn.huiyunche.bms.web.query.WayBillDetailQuery;
import cn.huiyunche.bms.web.vo.PayableBillVO;
import cn.huiyunche.bms.web.vo.PaymentVO;
import cn.huiyunche.commons.domain.PageVo;
import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/7/7 0007.
 */

@Controller
@RequestMapping("/payable")
public class PayableController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PayableController.class);

    @Autowired
    private PayableService payableService;

    /**
     * 跳转列表页面
     * @return
     * @throws Exception
     */
    @RequestMapping("/to-index")
    public String toListPage(HttpServletResponse response) throws Exception{
        response.setHeader("X-Frame-Options","SAMEORIGIN");
        return "index";
    }

    /**
     * 查询账单 带分页
     * @param pageVo
     * @param query
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/payable-list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> listByPage(PageVo pageVo, PayableBillQuery query) throws Exception {
        LOGGER.info("PayableController.listByPage params : {}, {}", pageVo, query);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            PayableBillConditions conditions = new PayableBillConditions();
            BeanUtils.copyProperties(query,conditions);
            result.setData(payableService.selectListByConditions(pageVo, conditions));
        } catch (Exception e) {
            LOGGER.error("PayableController.listByPage error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * List result.
     * 查询账单 不带分页
     * @param query the query
     * @return the result
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> list(PayableBillQuery query) throws Exception {
        LOGGER.info("PayableController.list param : {}", query);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            PayableBillConditions conditions = new PayableBillConditions();
            BeanUtils.copyProperties(query,conditions);
            result.setData(payableService.selectListByConditions(null, conditions).get("list"));
        } catch (Exception e) {
            LOGGER.error("PayableController.list error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }


    /**
     * 新建账单
     * @param query
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/waybill-list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> waybillList(PageVo pageVo, WayBillDetailQuery query) throws Exception {
        LOGGER.info("PayableController.waybillList params : {}, {}", pageVo, query);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            WayBillDetailConditions conditions = new WayBillDetailConditions();
            BeanUtils.copyProperties(query,conditions);

            if(StringUtils.isNotBlank(query.getWaybillCode())){
                String[] string = query.getWaybillCode().split(" ");
                List list = Arrays.asList(string);
                List list1 = new ArrayList();
                for (int i = 0; i < list.size(); i++) {
                    list1.add(list.get(i));
                }
                conditions.setWaybillCode(list1);
            }

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            if (query.getCreateTimeStart() != null)
                conditions.setCreateTimeStart(format.parse(query.getCreateTimeStart()));
            if (query.getCreateTimeEnd() != null)
                conditions.setCreateTimeEnd(format.parse(query.getCreateTimeEnd()));
            result.setData(payableService.selectWaybillDetaiByConditions(pageVo, conditions));
        } catch (Exception e) {
            LOGGER.error("PayableController.waybillList error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }


    /**
     * 新建账单 下一步 将数据插入临时表
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/insert-temp", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> insertTemp(PayableBillVO vo) throws Exception {
        LOGGER.info("PayableController.insertTemp params : {}, {}", vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "插入成功");
        try {
            result.setData(payableService.insertTemp(vo.getIds()));
        } catch (Exception e) {
            LOGGER.error("PayableController.insertTemp error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 新建账单下一步成功插入后展示
     * @param versionNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/select-temp-list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> selectTempListByVersionNo(String versionNo) throws Exception {
        LOGGER.info("PayableController.selectTempListByVersionNo params : {}, {}", versionNo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            result.setData(payableService.selectTempListByVersionNo(versionNo));
        } catch (Exception e) {
            LOGGER.error("PayableController.selectTempListByVersionNo error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 新建账单 下一步 将数据插入临时表并展示
     * @param ids
     * @return
     * @throws Exception
     */
//    @RequestMapping(value = "/waybill-list-next", method = RequestMethod.POST)
//    public
//    @ResponseBody
//    ResultDTO<Object> waybillListNext(String ids) throws Exception {
//        LOGGER.info("PayableController.waybillListNext params : {}, {}", ids);
//        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
//        try {
//            result.setData(payableService.selectWaybillDetaiByIds(ids));
//        } catch (Exception e) {
//            LOGGER.error("PayableController.waybillListNext error: {}", e);
//            throw new BusinessException(e.getMessage());
//        }
//        return result;
//    }


    /**
     * 获取调整金额
     * @param
     * @return
     * @throws Exception
     */
//    @RequestMapping(value = "/get-alter-cost", method = RequestMethod.POST)
//    public
//    @ResponseBody
//    String getAlterCost(Model model , Integer id) throws Exception {
//        LOGGER.info("PayableController.getAlterCost params : {}, {}", id);
//        ResultDTO<Object> result = new ResultDTO<>(true, null, "获取成功");
//        try {
//            result.setData(payableService.getAlterCost(id));
//        } catch (Exception e) {
//            LOGGER.error("PayableController.getAlterCost error: {}", e);
//            throw new BusinessException(e.getMessage());
//        }
//        model.addAttribute("result",result);
//        return "index";
//    }


    /**
     * 新建生成账单修改调整金额
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update-temp-cost", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> updateAlterCost(PayableBillVO payableBillVO) throws Exception {
        LOGGER.info("PayableController.updateAlterCost params : {}, {}", payableBillVO);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "修改成功");
        try {
            PayableBillBO payableBillBO = new PayableBillBO();
            BeanUtils.copyProperties(payableBillVO ,payableBillBO);
            result.setData(payableService.updateAlterCost(payableBillBO));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("PayableController.updateAlterCost error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 生成账单页面移除操作
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete-payable-fee-detail-temp", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> deletePayableFeeDetailTemp(Integer id ,Model model) throws Exception {
        LOGGER.info("PayableController.deletePayableFeeDetail params : {}, {}", id);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "移除成功");
        try {
            result.setData(payableService.deletePayableFeeDetailTemp(id));
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("PayableController.deletePayableFeeDetail error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 生成账单
     * @param versionNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/generate-bill", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> generateBill(String versionNo ,String invoiceStatus) throws Exception {
        LOGGER.info("PayableController.generateBill params : {}, {}", versionNo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "生成账单成功");
        try {
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            String username = (String)session.getAttribute("username");
            result.setData(payableService.generateBill(versionNo ,invoiceStatus ,username));
        } catch (Exception e) {
            LOGGER.error("PayableController.generateBill error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }


    /**
     * 删除账单
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete-payable", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> deletePayable(PayableBillVO vo) throws Exception {
        LOGGER.info("PayableController.deletePayable params : {}, {}", vo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "删除成功");
        try {
            payableService.deletePayable(vo.getIds());
        } catch (Exception e) {
            result.setSuccess(false);
            LOGGER.error("PayableController.deletePayable error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }


    /**
     * 账单列表页面确认账单
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/confirm-payable-bill", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> confirmPayableBill(Integer id, PageVo pageVo) throws Exception {
        LOGGER.info("PayableController.confirmPayableBill params : {}, {}", id);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "确认账单跳转成功");
        try {
            result.setData(payableService.confirmPayableBill(id , pageVo));
        } catch (Exception e) {
            LOGGER.error("PayableController.confirmPayableBill error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 确认账单页面移除操作(正式表)
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete-payable-fee-detail", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> deletePayableFeeDetail(Integer id) throws Exception {
        LOGGER.info("PayableController.deletePayableFeeDetail params : {}, {}", id);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "移除成功");
        try {
            result.setData(payableService.deletePayableFeeDetail(id));
        } catch (Exception e) {
            LOGGER.error("PayableController.deletePayableFeeDetail error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 确认账单页面获取调整金额
     * @param
     * @return
     * @throws Exception
     */
//    @RequestMapping(value = "/get-payable-fee-detail", method = RequestMethod.POST)
//    public
//    @ResponseBody
//    String getPayableFeeDetail(Model model , Integer id) throws Exception {
//        LOGGER.info("PayableController.getPayableFeeDetail params : {}, {}", id);
//        ResultDTO<Object> result = new ResultDTO<>(true, null, "获取成功");
//        try {
//            result.setData(payableService.getPayableFeeDetail(id));
//        } catch (Exception e) {
//            LOGGER.error("PayableController.getPayableFeeDetail error: {}", e);
//            throw new BusinessException(e.getMessage());
//        }
//        model.addAttribute("result",result);
//        return "index";
//    }

    /**
     * 修改正式表调整金额
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update-payable-fee-detail", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> updatePayableFeeDetail(PayableBillVO payableBillVO) throws Exception {
        LOGGER.info("PayableController.updatePayableFeeDetail params : {}, {}", payableBillVO);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "修改成功");
        try {
            PayableBillBO payableBillBO = new PayableBillBO();
            BeanUtils.copyProperties(payableBillVO ,payableBillBO);
            result.setData(payableService.updatePayableFeeDetail(payableBillBO));
        } catch (Exception e) {
            LOGGER.error("PayableController.updateAlterCost error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 确认账单中确认账单按钮
     * @param invoiceStatus
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/create-payable-bill", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object>  createPayableBill(String invoiceStatus,Integer billId ) throws Exception {
        LOGGER.info("PayableController.createPayableBill params : {}, {}", invoiceStatus);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "确认账单页面确认账单跳转成功");
        try {
            result.setData(payableService.createPayableBill(invoiceStatus ,billId));
        } catch (Exception e) {
            LOGGER.error("PayableController.createPayableBill error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }


    /**
     * 付款管理页面
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/payment-list-init", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object> paymentListInit(PageVo pageVo, PayableBillQuery query) throws Exception {
        LOGGER.info("PayableController.paymentListInit params : {}, {}", pageVo, query);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "查询成功");
        try {
            PayableBillConditions conditions = new PayableBillConditions();
            BeanUtils.copyProperties(query,conditions);
            result.setData(payableService.selectPaymentList(pageVo, conditions));
        } catch (Exception e) {
            LOGGER.error("PayableController.paymentListInit error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }


    /**
     * 付款管理付款确认按钮
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/payment-list", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object>  paymentList(Integer id) throws Exception {
        LOGGER.info("PayableController.paymentList params : {}, {}", id);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "付款跳转成功");
        try {
            result.setData(payableService.paymentList(id));
        } catch (Exception e) {
            LOGGER.error("PayableController.paymentList error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 付款管理确认付款
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/confirm-payment", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultDTO<Object>  confirmPayment(PaymentVO formVo) throws Exception {
        LOGGER.info("PayableController.confirmPayment params : {}, {}", formVo);
        ResultDTO<Object> result = new ResultDTO<>(true, null, "确认付款成功");
        try {
            PaymentBO formBo = new PaymentBO();
            BeanUtils.copyProperties(formVo ,formBo);

            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
            if(StringUtils.isNotBlank(formVo.getInvoiceDate() )){
                formBo.setInvoiceDate(sim.parse(formVo.getInvoiceDate())) ;
            }
            if(StringUtils.isNotBlank(formVo.getPayDate())){
                formBo.setPayDate(sim.parse(formVo.getPayDate()));
            }
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            String usercomment = (String)session.getAttribute("usercomment");
            formBo.setUsername(usercomment);
            result.setData(payableService.confirmPayment(formBo));
        } catch (Exception e) {
            LOGGER.error("PayableController.confirmPayment error: {}", e);
            throw new BusinessException(e.getMessage());
        }
        return result;
    }

    /**
     * 批量导出账单
     * @param vo
     * @return
     */
    @RequestMapping(value = "/export-bill-detail" ,method = RequestMethod.GET)
    @ResponseBody
    public void exportBillDetail(PayableBillVO vo, HttpServletResponse res){
        LOGGER.info("PayableController.exportBillDetail params : {}, {}", vo);
        try {
            payableService.exportBillDetail(vo.getIds(),res);
        } catch (Exception e) {
            LOGGER.error("PayableController.exportBillDetail error: {}", e);
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 付款确认批量导出账单
     * @param vo
     * @return
     */
    @RequestMapping(value = "/export-payment" ,method = RequestMethod.GET)
    @ResponseBody
    public void exportPayment(PayableBillVO vo, HttpServletResponse res){
        LOGGER.info("PayableController.exportPayment params : {}, {}", vo);
        try {
            payableService.exportPayment(vo.getIds(),res);
        } catch (Exception e) {
            LOGGER.error("PayableController.exportPayment error: {}", e);
            throw new BusinessException(e.getMessage());
        }
    }


}
